﻿using UnityEngine;
using System.Collections;

public class FogOfWar : MonoBehaviour {
	private Texture2D fogofwar;
	public Player myPlayer;
	public MapInfo mapInfo;
	private int count=0;
	// Use this for initialization
	void Start () {
		fogofwar = new Texture2D(512,512);
		//fogofwar.alphaIsTransparency=true;
		fogofwar.wrapMode=TextureWrapMode.Clamp;
		Color[] pixels = fogofwar.GetPixels ();
		for(int i=0;i<pixels.Length;i++){
			pixels[i]=Color.black;
			pixels[i].a=.9f;
		}
		fogofwar.SetPixels(pixels);
		fogofwar.Apply();
		this.renderer.enabled=true;
		this.renderer.material.SetTexture("_MainTex",fogofwar);
	}

	int convertX(double x){
		return (int)(512-(512*(x+100)/200));
		//double d=mapInfo.convertX(x);
		//return (int)(512-(int)(512*mapInfo.convertX(x)));
	}

	int convertZ(double z){
		return (int)(512-(512*(z+100)/200));
		//double d=mapInfo.convertZ(z);
		//return (int)((512-(int)(512*mapInfo.convertZ(z))));
	}

	// Update is called once per frame
	void Update () {
		if(count++>=10){
			Color[] pixels = fogofwar.GetPixels ();
			for(int i=0;i<pixels.Length;i++){
				pixels[i]=Color.black;
				pixels[i].a=.9f;
			}
			fogofwar.SetPixels(pixels);
			foreach(Unit u in myPlayer.getUnits()){
				int sight=64,sx=sight,sy=sight;
				int cx=convertX(u.obj.transform.position.x),cy=convertZ(u.obj.transform.position.z);
				int x= cx-sight/2,
					y=cy-sight/2;
				if(x<0)
					x=0;
				if(y<0)
					y=0;
				if(x>512)x=512;
				if(y>512)y=512;
				if(x+sx>512)
					sx=512-x;
				if(y+sy>512)
					sy=512-y;
				pixels = fogofwar.GetPixels (x,y,sx,sy);
				for(int i=0;i<pixels.Length;i++){
					int mX=i%sx,mY=i/sy;
					if(mX==0 || mY==0|| mX>sx-1 || mY>sy-1)
						pixels[i].a=Mathf.Min(.5f,pixels[i].a);
					else
						pixels[i].a=0;
					//float tst=(sight*8f/9-Mathf.Sqrt((Mathf.Pow(mX-sx/2,2)+Mathf.Pow(mY-sy/2,2))))*2f/sight;
					//pixels[i].a=Mathf.Min(1.0f-Mathf.Max(tst,0),pixels[i].a);
				}
				fogofwar.SetPixels(x,y,sx,sy,pixels);
			}

			fogofwar.Apply();
			count=0;
		}
	}
}
